﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using xmgl.Dal;
using xmgl.Models;

namespace xmgl.Controllers
{
    public class BookController : Controller
    {
        protected log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        protected DbBaseContext db = new DbBaseContext();
        // GET: Book
        public ActionResult Index()
        {
            var books = from b in db.Books
                        where b.Price > 0
                        select b;
            return View(books.ToList());
        }

        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Create(Book bean)
        {
            var res = new JsonResult();
            try
            {
                if (ModelState.IsValid)
                {
                    db.Books.Add(bean);
                    db.SaveChanges();
                    res.Data = new { error = false, msg = "保存成功" };
                }
                Log.Debug("...............");
            }
            catch (Exception ex)
            {
                res.Data = new { error = true, msg = "保存出错" };
                Log.Error(ex);
            }
            return res;
        }


        public ActionResult Edit(int id)
        {
            Book blog = db.Books.Find(id);
            return View(blog);
        }

        [HttpPost]
        public ActionResult Edit(Book bean)
        {
            if (ModelState.IsValid)
            {
                db.Entry(bean).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(bean);
        }

        public ActionResult Delete(int id)
        {
            Book blog = db.Books.Find(id);
            return View(blog);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Book blog = db.Books.Find(id);
            db.Books.Remove(blog);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}